<template>
  <view style="width: 100%">
    <u--input v-model="currentData" :placeholder="placeholder" :suffix-icon="suffixIcon" readonly @click="click"/>
    <u-picker :show="show" :columns="list" @cancel="cancel" @confirm="confirm"/>
  </view>
</template>

<script>
export default {
  name: 'ListPicker',
  props: {
    modelValue: {
      type: String,
      default: undefined
    },
    placeholder: {
      type: String,
      default: ''
    },
    suffixIcon: {
      type: String,
      default: 'grid-fill'
    },
    width: {
      type: String,
      default: '100%'
    },
    columns: {
      type: Array,
      default: function () {
        return []
      }
    },
    props: {
      type: Object,
      default() {
        return { value: 'value', label: 'label' }
      }
    }
  },
  data() {
    return {
      list: [],
      show: false,
      currentData: undefined
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        if (val) {
          this.list.forEach(col => {
            col.forEach(item => {
              if (item.value === val) {
                this.currentData = item.text
              }
            })
          })
        }
      }
    },
    columns: {
      immediate: true,
      handler(val) {
        if (val) {
          this.list = []
          const col = []
          val.forEach(column => {
            const item = {}
            item.text = column[this.props.label]
            item.value = column[this.props.value]
            if (item.value === this.modelValue) {
              this.currentData = item.text
            }
            col.push(item)
          })
          this.list.push(col)
        }
      }
    }
  },
  methods: {
    click() {
      this.show = true
    },
    cancel() {
      this.show = false
    },
    confirm(e) {
      this.currentData = e.value[0].text
      this.$emit('update:modelValue', e.value[0].value)
      this.show = false
    }
  }
}
</script>
<style lang="scss" scoped>
:deep(.u-icon__icon) {
  color: $u-primary !important;
}
</style>
